import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import AssetView from '../views/AssetView.vue'
import RoomView from '../views/RoomView.vue'
import GatewayView from '../views/GatewayView.vue'
import MessageView from '../views/MessageView.vue'
import scan from '../views/scan.vue'
import map from '../views/map.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
  },
  {
    path: '/',
    name: 'Home',
    component: HomeView,
    meta: { requiresAuth: true },
  },
  {
    path: '/asset',
    name: 'Asset',
    component: AssetView,
    meta: { requiresAuth: true },
  },
  {
    path: '/room',
    name: 'Room',
    component: RoomView,
    meta: { requiresAuth: true },
  },
  {
    path: '/gateway',
    name: 'Gateway',
    component: GatewayView,
    meta: { requiresAuth: true },
  },
  {
    path: '/message',
    name: 'Message',
    component: MessageView,
    meta: { requiresAuth: true },
  },
  {
    path: '/scan',
    name: 'scan',
    component: scan,
    meta: { requiresAuth: true },
  },
  {
    path: '/map',
    name: 'map',
    component: map,
    meta: { requiresAuth: true },
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next('/')
  } else {
    next()
  }
})

export default router
